package com.ruoyi.chiwen.controller.api;


import com.ruoyi.chiwen.domain.TbAudit;
import com.ruoyi.chiwen.domain.TbUser;
import com.ruoyi.chiwen.service.ITbAuditService;
import com.ruoyi.chiwen.service.ITbUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.UserTokenService;
import com.ruoyi.framework.web.service.WxLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * app 审批接口
 *
 * @author tf
 */
@RestController
@RequestMapping("/chiwen/auditapi")
public class AuditApiController {


    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private ITbAuditService tbAuditService;

    @Autowired
    private ITbUserService tbUserService;
//  月利率  后期修改
    static final double lilv = 0.005;

    /**
     * 查询个人额度
     * @param request  获取token
     * @return
     */
    @GetMapping("/getAuditInfo")
    public AjaxResult getAuditInfo(HttpServletRequest request){
        String token = userTokenService.getToken(request);
        WxLoginUser wxLoginUser = userTokenService.getWxLoginUser(token);
        TbAudit tbAudit = new TbAudit();
//        查询贷款记录
        tbAudit.setUserId(wxLoginUser.getUserId());
        List<TbAudit> tbAudits = tbAuditService.selectTbAuditList(tbAudit);
//        查询个人信息额度
        TbUser tbUsers = tbUserService.selectTbUserById(wxLoginUser.getUserId());
//        已经借
        Long allTotal = 0L;

        for (TbAudit audit:tbAudits ) {
//            把已同意和待审批的额度相加
            if(audit.getaStatus() == 1 || audit.getaStatus() == 0){
               if(audit.getaMoneyNumber()!=null) allTotal += audit.getaMoneyNumber();

            }
        }
//        剩余可用金额     总额度- 已审批的额度
        Long remainMoney = tbUsers.getAvailableCredit() - allTotal;

        return AjaxResult.success(remainMoney);
    }

    /**
     *
     * @param mothNum 分期数
     * @param moneyTotal  总金额
     * @return  每期应还金额
     */
    @GetMapping("/calculateMoney")
    public AjaxResult calculateMoney(Integer mothNum,double moneyTotal){
        //每月还款额=贷款本金×[月利率×(1+月利率) ^ 还款月数]÷{[(1+月利率) ^ 还款月数]-1}。
//        利率
//        double lilv = 0.005;
//        (1+月利率)
        double interestTotal = 1 + lilv;
//        接收 (1+月利率) ^ 还款月数的值
        double interestMoneyTotal = 0;
        interestMoneyTotal = interestTotal * 1;
        for (int i = 1; i < mothNum; i++) {
            interestMoneyTotal = interestMoneyTotal * interestTotal;
        }
        // (1+月利率) ^ 还款月数
        BigDecimal bigDecimal =new BigDecimal(interestMoneyTotal);
        BigDecimal cifang = bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP);
//        console.log("(1+月利率) ^ 还款月数:----",cifang);
//        利率 decimal化
        BigDecimal lilv1 =new BigDecimal(lilv);
        BigDecimal l =new BigDecimal(1);
//        贷款金额
        BigDecimal moneyTotalBig =new BigDecimal(moneyTotal);
//        每月还款额=贷款本金×[月利率×(1+月利率) ^ 还款月数]÷{[(1+月利率) ^ 还款月数]-1}。
        BigDecimal month_val = moneyTotalBig.multiply(lilv1.multiply(cifang)).divide(cifang.subtract(l),2, BigDecimal.ROUND_HALF_UP);
        return AjaxResult.success(month_val);
    }

    /**
     * 提交审批
     * @param tbAudit  审批信息
     * @return
     */
    @PostMapping("/subAudit")
    public AjaxResult subAudit(@RequestBody  TbAudit tbAudit, HttpServletRequest request){

//        先检查是否有未通过的审批
        String token = userTokenService.getToken(request);
        WxLoginUser wxLoginUser = userTokenService.getWxLoginUser(token);
        TbAudit audit = new TbAudit();
        audit.setUserId(wxLoginUser.getUserId());
        List<TbAudit> tbAudits = tbAuditService.selectTbAuditList(audit);
        if(tbAudits == null || tbAudits.size() == 0){

        }else{
            for (int i = 0; i < tbAudits.size(); i++) {
                if(tbAudits.get(i).getaStatus() == 0){
                    return AjaxResult.error("您有待处理的申请");
                }else if(tbAudits.get(i).getaStatus() == 2){
                    return AjaxResult.error("您有被拒绝的申请，无法再次申请");
                }
            }
        }

//        利率
        BigDecimal lilvbig = new BigDecimal(lilv);
        tbAudit.setUserId(wxLoginUser.getUserId());
        tbAudit.setaStatus(0);
        tbAudit.setaInterestRate(lilvbig);
        tbAudit.setIsAccount(0);
        tbAudit.setCreateTime(new Date());
        tbAuditService.insertTbAudit(tbAudit);
        return AjaxResult.success("已提交申请");
    }

    @PostMapping("/getAuditByUser")
    public AjaxResult getAuditByUser(HttpServletRequest request){
        String token = userTokenService.getToken(request);
        WxLoginUser wxLoginUser = userTokenService.getWxLoginUser(token);
        TbAudit tbAudit = new TbAudit();
        tbAudit.setUserId(wxLoginUser.getUserId());
        List<TbAudit> tbAudits = tbAuditService.selectTbAuditList(tbAudit);
        return AjaxResult.success(tbAudits);
    }

    @GetMapping("/getOrderDetialByaId")
    public AjaxResult getOrderDetialByaId(Long aId){
        TbAudit tbAudit = tbAuditService.selectTbAuditById(aId);
        return AjaxResult.success(tbAudit);
    }


        @GetMapping("/getContractInfo")
    public AjaxResult getContractInfo(Long aId){
        List<Map<String, Object>> contractInfo = tbAuditService.getContractInfo(aId);
        return AjaxResult.success(contractInfo.get(0));
    }

}
